package com.zhxxfwzx.security;

import cn.hutool.core.util.StrUtil;
import com.zhxxfwzx.entity.SysUser;
import com.zhxxfwzx.service.SysUserService;
import com.zhxxfwzx.service.details.MyUserDetailsService;
import com.zhxxfwzx.utils.JwtTokenUtils;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.JwtException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.web.authentication.www.BasicAuthenticationFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @Description TODO
 * @title: JwtAuthenticationFilter
 * @Author LiJing
 * @Date: 2021/6/167:21 下午
 * @Version 1.0
 */
@Slf4j
public class JwtAuthenticationFilter extends BasicAuthenticationFilter {
    @Autowired
    JwtTokenUtils jwtTokenUtils;
    @Autowired
    SysUserService sysUserService;
    @Autowired
    MyUserDetailsService myUserDetailsService;

    public JwtAuthenticationFilter(AuthenticationManager authenticationManager) {
        super(authenticationManager);
    }

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws IOException, ServletException {
        //获取请求头带过来的jwtToken
        String jwt = request.getHeader(jwtTokenUtils.getHeader());
        if (StrUtil.isBlankOrUndefined(jwt)){
            chain.doFilter(request, response);
            return;
        }
        Claims claim = jwtTokenUtils.getClaimsFromToken(jwt);
        if (claim == null){
            throw new JwtException("token异常");
        }
        if (jwtTokenUtils.isTokenExpired(jwt)){
            throw new JwtException("token已过期");
        }
        String username = jwtTokenUtils.getUsernameFromToken(jwt);
        log.info("用户-{},正在登录!", username);


        SysUser user = sysUserService.getUserByUsername(username);
        if (user == null){
            throw new UsernameNotFoundException("该用户不存在");
        }


        UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(user,user.getPassword(), myUserDetailsService.getUserAuthority(user.getUserId()));
        SecurityContextHolder.getContext().setAuthentication(token);

        chain.doFilter(request, response);

    }
}
